package com.moji.util;

import com.moji.entity.SysDept;
import com.moji.entity.dto.TreeDto;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class DeptTreeUtil {
    /**
     * list集合的行数据，转换成 tree 结构
     * @param list CcpSystemDept
     * @return
     */
    public static List<TreeDto> list2Tree(List<SysDept> list) {
        List<TreeDto> result = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            for(SysDept d : list){
                if(d.getParentCode() == null || "0".equals(d.getParentCode())) {
                    TreeDto vo = new TreeDto(d.getId()+"",d.getDeptCode(), d.getDeptName(),d.getParentCode(),d.getParentName(),d.getOrderNo()+"",d.getDeptLevel()+"",null,d.getDeptPath());
                    vo.setTreeList(recurrence(list, d));
                    result.add(vo);
                }
            }
        }
        return result;
    }
    /**
     *  递归函数
     * @param list
     * @param vo
     */
    private static List<TreeDto> recurrence(List<SysDept> list, SysDept vo) {
        List<TreeDto> subNodes = new ArrayList<>();
        for (SysDept d : list) {
            if (vo.getDeptCode().equals(d.getParentCode())) {
                TreeDto sub = new TreeDto(d.getId()+"",d.getDeptCode(), d.getDeptName(),d.getParentCode(),d.getParentName(),d.getOrderNo()+"",d.getDeptLevel()+"",null,d.getDeptPath());
                sub.setTreeList(recurrence(list, d));
                subNodes.add(sub);
            }
        }
        return subNodes;

    }

}
